//
//  UIViewController.swift
//  reactsdk
//
//  Created by Валиева Анна Евгеньевна on 02.04.2024.
//

import UIKit

extension UIViewController {
    static var current: UIViewController? {
        if let rootViewController = UIApplication.shared.keyWindow?.rootViewController {
            return findTopViewController(controller: rootViewController)
        }
        return nil
    }

    private static func findTopViewController(controller: UIViewController) -> UIViewController {
        if let presentedViewController = controller.presentedViewController {
            return findTopViewController(controller: presentedViewController)
        }
        if let navigationController = controller as? UINavigationController,
            let visibleViewController = navigationController.visibleViewController {
            return findTopViewController(controller: visibleViewController)
        }
        if let tabBarController = controller as? UITabBarController,
            let selectedViewController = tabBarController.selectedViewController {
            return findTopViewController(controller: selectedViewController)
        }
        return controller
    }
}
